<?php
namespace Framework\Http;

use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
// use Framework\Http\Seesion;

class Request extends SymfonyRequest
{
    /**
     * 中间件传递的参数
     * @var array
     */
    protected $middleware = [];

    protected $_session_class;

    public function session(){
        // if( $this->_session_class == null ){
        //     $className = app()->config->get('session._class');
        //     $this->_session_class = new $className();
        // }

        // return $this->_session_class;
        return new \Framework\Extensions\RedisSession();
    }


    public function path(){
        $pattern = trim($this->getPathInfo(), '/');

        return $pattern == '' ? '/' : $pattern;
    }

    public function method()
    {
        return $this->getMethod();
    }

    public function root()
    {
        return rtrim($this->getSchemeAndHttpHost().$this->getBaseUrl(), '/');
    }

    /**
     * Get the URL (no query string) for the request.
     *
     * @return string
     */
    public function url()
    {
        return rtrim(preg_replace('/\?.*/', '', $this->getUri()), '/');
    }

    public function ip()
    {
        return $this->getClientIp();
    }
    
    public function is($patterns){
        $path = trim($this->path(), '/');

        if( !strstr($patterns, '*') ){ 
            //完全匹配模式
            return ($patterns==$path) ? true : false ;
        }

        //通配符模式
        $patterns = str_replace('/', '\/', $patterns);
        $rule = str_replace('*', '([A-Za-z0-9\-\_\/]+)', $patterns);
        $rule = '/^' . $rule . '$/';
 
        return is_scalar($path) && 1 === preg_match($rule, (string) $path);
    }



    public function cookie($name)
    {
        return isset($_COOKIE[$name]) ? $_COOKIE[$name] : '' ;
    }



    /**
     * 获得可用的session驱动
     */
    public function sessionDrivers($driver)
    {
        return [
            'file'  => Session::class,
            'redis' => Framework\Extensions\RedisSession::class,
        ];
    }


    /**
     * 获取中间件传递的参数
     * @access public
     * @param  mixed $name 变量名
     * @param  mixed $default 默认值
     * @return mixed
     */
    public function middleware($name, $default = null)
    {
        return $this->middleware[$name] ?? $default;
    }

    /**
     * 设置中间传递数据
     * @access public
     * @param  string    $name  参数名
     * @param  mixed     $value 值
     */
    public function __set(string $name, $value)
    {
        $this->middleware[$name] = $value;
    }

    /**
     * 获取中间传递数据的值
     * @access public
     * @param  string $name 名称
     * @return mixed
     */
    public function __get(string $name)
    {
        return $this->middleware($name);
    }

    /**
     * 检测中间传递数据的值
     * @access public
     * @param  string $name 名称
     * @return boolean
     */
    public function __isset(string $name): bool
    {
        return isset($this->middleware[$name]);
    }

}